package marchsoft.modules.tiku.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import marchsoft.annotation.rest.AnonymousGetMapping;
import marchsoft.annotation.rest.AnonymousPostMapping;
import marchsoft.base.PageVO;
import marchsoft.enums.ResultEnum;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.tiku.entity.EStudent;
import marchsoft.modules.tiku.entity.dto.EStudentQueryCriteria;
import marchsoft.modules.tiku.entity.dto.StudentDto;
import marchsoft.modules.tiku.entity.dto.StudentExcel;
import marchsoft.modules.tiku.listener.StudentListener;
import marchsoft.modules.tiku.service.IEStudentService;
import marchsoft.modules.upload.controller.FileController;
import marchsoft.modules.upload.service.FileService;
import marchsoft.response.Result;
import marchsoft.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Set;



/**
 * <p>
 * 学生基本信息表 前端控制器
 * </p>
 * @author wjy
 * @since 2022-04-18
 */
@RequiredArgsConstructor
@RestController
@Slf4j
@Api(tags = "学生基本信息表模块")
@RequestMapping("/api/eStudent")
public class EStudentController {
    private final IEStudentService eStudentService;
    private final PasswordEncoder passwordEncoder;

    private final FileController fileController;
    private final FileService fileService;

    @ApiOperation(value = "条件查询学生(分页)")
    @GetMapping
    public Result<IPage<StudentDto>> findStudent(PageVO page, EStudentQueryCriteria criteria) {
        page.setOrders("[{'column': 's.create_time','asc': false}]");
        return Result.success(eStudentService.findStudent(page.buildPage(), criteria));
    }


    @ApiOperation(value = "修改学生信息", notes = " \n")
    @PutMapping
    public Result<Void> updateStudent(@RequestBody EStudent student) {
        eStudentService.updateOrCreateStudent(student);
        return Result.success();
    }

    @ApiOperation(value = "新增学生", notes = " \n")
    @PostMapping
    public Result<Void> addStudent(@RequestBody EStudent student) {
        // 初始化学生密码
        student.setPassword(passwordEncoder.encode("123456"));
        eStudentService.updateOrCreateStudent(student);
        return Result.success();
    }


    @ApiOperation(value = "删除学生", notes = " \n")
    @DeleteMapping
    public Result<Void> deleteStudent(@RequestBody Set<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            log.error(StrUtil.format("【删除学生失败】学生ID不能为空。操作人id：{}，删除学生id：{}", SecurityUtils.getCurrentUserId(), ids));
            throw new BadRequestException(ResultEnum.PARAM_IS_BLANK);
        }
        eStudentService.removeByIds(ids);
        return Result.success();
    }

    @ApiOperation("导出学生数据")
    @GetMapping("/download")
    @PreAuthorize("@smpe.check('dept:list')")
    public void download(HttpServletResponse response, EStudentQueryCriteria criteria) throws Exception {
        log.info(StrUtil.format("【导出学生数据 /api/eSafeCase/download】操作人id：{}，案例查询条件 criteria：{}", SecurityUtils.getCurrentUserId(),
                criteria));
        eStudentService.download(eStudentService.queryAll(criteria, false), response);
    }

    @AnonymousPostMapping("/import")
    @ResponseBody
    public Result<Object> importLoad(@RequestPart MultipartFile file) throws Exception {
        // easyExcel解析
        EasyExcel.read(file.getInputStream(), StudentExcel.class,new StudentListener(eStudentService)).sheet().doRead();
        return Result.success();
    }

    @GetMapping("/info")
    public Result<Object> selectInfo(){
        EStudent eStudent=eStudentService.getById(SecurityUtils.getCurrentUserId());
        return Result.success(eStudent);
    }

}
